package com.apes.fn.scm.merchant.account.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.*;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.merchant.account
 * @ClassName: MerchantSettlement
 * @Author: pyb
 * @CreateTime: 2021-09-29 16:19
 * @Description: 赋能商户结算对账单2.0
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = MerchantAccountSettlement.CONST_TABLE_NAME)
public class MerchantAccountSettlement extends Model {
    public static final String CONST_TABLE_NAME = "merchant_account_settlement";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "赋能结算对账单编码", padding = 10, prefix = "%(merchant)")
    @Comment("编码")
    private String id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "merchant_id", referencedColumnName = "id")
    @Comment("商户编码")
    private PartyRole merchant;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "reconcile_begin_date")
    @Comment("开始对账日期")
    private Date reconcileBeginDate;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "reconcile_end_date")
    @Comment("结束对账日期")
    private Date reconcileEndDate;


    @Column(name = "state", length = 36, nullable = false)
    @States(name = "订单状态", values = {
            @State(id = "sent", name = "新建"),
            @State(id = "pending", name = "待排款"),
            @State(id = "done", name = "已完成"),
            @State(id = "confirmation", name = "商户确认"),
            @State(id = "financialAudit", name = "财务审计"),
            @State(id = "arrangement", name = "排款中"),
            @State(id = "pay", name = "部分付款"),
            @State(id = "payment", name = "已付款")})
    private String state;


    @Column(name = "state_accounts", length = 36, nullable = false)
    @Comment("是否清账")//squareAccounts已清账，outstandingAccount未清账
    private String stateAccounts;

    public void setInventoryMoney() {
        this.inventoryMoney = SpringManager.getBean(InventoryBatchRepository.class).findStandingInventoryAmount(getMerchant().getId());
    }

    @Column(name = "inventory_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("常备库存金额")
    private double inventoryMoney = 0;

    @Column(name = "outstanding_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("挂账未清款")
    private double outstandingMoney = 0;

    @Column(name = "un_invoiced_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未开发票金额")
    private double unInvoicedMoney = 0;

    @Column(name = "pre_settle_business_money", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("前期应结算金额")
    private double preSettleBusinessMoney = 0;

    @Column(name = "should_settle_business_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期应结算营业款")
    private double shouldSettleBusinessMoney = 0;

    public void setSettleBusinessMoneyTotal() {
        this.settleBusinessMoneyTotal = Arith.round(getSettleBusinessMoneyTotal(), 2);
    }

    @Column(name = "settle_business_money_total", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计应结算金额")
    private double settleBusinessMoneyTotal = 0;


    @Column(name = "total_current_income", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期营业收入合计")
    private double totalCurrentIncome = 0;

    @Column(name = "total_current_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期款项金额合计")
    private double totalCurrentAmount = 0;

    @Column(name = "total_current_platform_fee", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期平台服务费合计")
    private double totalCurrentPlatformFee = 0;


    @Column(name = "total_cost_previous", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("上期未扣收成本合计")
    private double totalCostPrevious = 0;

    @Column(name = "totalCurrentAddCost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期新增成本合计")
    private double totalCurrentAddCost = 0;


    @Column(name = "total_current_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期实际扣收成本合计")
    private double totalCurrentCost = 0;


    @Column(name = "total_un_deducted_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未扣收成本合计")
    private double totalUnDeductedCost = 0;


    @Column(name = "total_expense_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期扣收费用成本合计")
    private double totalExpenseCost = 0;


    @Column(name = "total_expense_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("费用合计")
    private double totalExpenseAmount = 0;

    @Column(name = "total_previous_expense", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("前期扣收费用合计")
    private double totalPreviousExpense = 0;

    @Column(name = "total_un_deducted_expense", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未扣收费用合计")
    private double totalUnDeductedExpense = 0;


    @Column(name = "total_business_debit_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期借支费用合计")
    private double totalBusinessDebitCost = 0;

    @Column(name = "total_debit_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("借支合计")
    private double totalDebitAmount = 0;

    @Column(name = "total_previous_debit", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("前期扣收借支合计")
    private double totalPreviousDebit = 0;

    @Column(name = "total_un_deducted_debit", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未扣收借支合计")
    private double totalUnDeductedDebit = 0;


    @Column(name = "note", length = 1000)
    @Comment("备注")
    private String note;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reconcile_uid", referencedColumnName = "id")
    @Comment("对账人")
    private PartyRole reconcileUid;

    @Column(name = "reconcile_date")
    @Comment("对账日期")
    private Date reconcileDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "service_approve_uid", referencedColumnName = "id")
    @Comment("客服审批人")
    private PartyRole serviceApproveUid;

    @Column(name = "service_approve_date")
    @Comment("客服审批日期")
    private Date serviceApproveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "square_accounts_uid", referencedColumnName = "id")
    @Comment("清账人")
    private PartyRole squareAccountsUid;

    @Column(name = "square_accounts_date")
    @Comment("清账日期")
    private Date squareAccountsDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "merchant_confirmation_uid", referencedColumnName = "id")
    @Comment("商户确认人")
    private PartyRole merchantConfirmationUid;

    @Column(name = "merchant_confirmation_date")
    @Comment("商户确认日期")
    private Date merchantConfirmationDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "financial_audit_uid", referencedColumnName = "id")
    @Comment("财务审计人")
    private PartyRole financialAuditUid;

    @Column(name = "financial_audit_date")
    @Comment("财务审计日期")
    private Date financialAuditDate;

    @Column(name = "first_financial_audit_date")
    @Comment("财务首次审计日期")
    private Date firstFinancialAuditDate;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;

    @Column(name = "invoice_apply_id", length = 256)
    @Comment("发票申请单号")
    private String invoiceApplyId;

    @Column(name = "accumulate", length = 256)
    @Comment("累计欠款")
    private String accumulate;

    public void setAccumulate() {
        this.accumulate = "总计应结算营业款（小于0时）：￥" + Arith.round(this.settleBusinessMoneyTotal < 1 ? this.settleBusinessMoneyTotal : 0, 2)
                + "- 分期剩余未扣收金额的总计：￥：" + Arith.round(this.totalUnDeductedCost, 2);
        this.accumulateSum = Arith.round(Arith.round(this.settleBusinessMoneyTotal < 1 ? this.settleBusinessMoneyTotal : 0, 2) - this.totalUnDeductedCost ,2);
    }

    @Column(name = "accumulate_sum", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("累计欠款金额")
    private double accumulateSum = 0;

    @Column(name = "last_period_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("上期定损金额")
    private double lastPeriodAmount = 0;

    @Column(name = "last_period", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("上期id")
    private String lastPeriod;

    @Column(name = "total_platform_servic_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期金额未入账总计")
    private double totalPlatformServiceAmount = 0;

    @Column(name = "total_disbursement_amount", columnDefinition = ApesConst.FIELD_16_4)
    @Comment("已排款金额总计")
    private double totalDisbursementAlreadyAmount = 0;

    @Column(name = "pay_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("付款金额")
    private double payAmount = 0;

    @Comment("商户确认回执")
    @Column(name = "merchant_address", length = 4000)
    private String merchantAddress;

    @Comment("付款回执")
    @Column(name = "file_address", length = 4000)
    private String fileAddres;

    @Column(name = "reconcile", length = 64)
    @Comment("办理人")
    private String reconcile;

    @Column(name = "total_oa", length = 64)
    @Comment("办理人")
    private String totalOa;

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fn_tag", referencedColumnName = "id")
    @Comment("赋能标签")
    private Enumeration fnTag;



    @Column(name = "candidates", length = 64)
    @Comment("部门")
    private String candidates;

    @Column(name = "auto_flag", columnDefinition = "number(2) default 0")
    @Comment("自动创建标识(0:否;1:是)")
    private int autoFlag;


    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MerchantAccountSubjects> merchantAccountSubjects = new ArrayList<>();//科目余额

    public List<MerchantAccountSubjects> getMerchantAccountSubjects() {
        if (merchantAccountSubjects == null) merchantAccountSubjects = new ArrayList<>();
        for (MerchantAccountSubjects subjects : merchantAccountSubjects) {
            subjects.setMerchantSettlement(this);
        }
        return merchantAccountSubjects;
    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MerchantBankAccount> merchantBankAccounts = new ArrayList<>();//银行账户

    public List<MerchantBankAccount> getMerchantBankAccounts() {
        if (merchantBankAccounts == null) merchantBankAccounts = new ArrayList<>();
        for (MerchantBankAccount bankAccount : merchantBankAccounts) {
            bankAccount.setMerchantSettlement(this);
        }
        return merchantBankAccounts;
    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SettlementCostSummary> costSummaries = new ArrayList<>();//营业支出

    public List<SettlementCostSummary> getCostSummaries() {
        if (costSummaries == null) costSummaries = new ArrayList<>();
        for (SettlementCostSummary costSummary : costSummaries) {
            costSummary.setMerchantSettlement(this);
        }
        return costSummaries;

    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SettlementIncomeSummary> incomeSummaries = new ArrayList<>();//营业收入

    public List<SettlementIncomeSummary> getIncomeSummaries() {
        if (incomeSummaries == null) incomeSummaries = new ArrayList<>();
        for (SettlementIncomeSummary incomeSummary : incomeSummaries) {
            incomeSummary.setMerchantSettlement(this);
        }
        return incomeSummaries;

    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SettlementExpenseItem> expenseItems = new ArrayList<>();//费用账单

    public List<SettlementExpenseItem> getExpenseItems() {
        if (expenseItems == null) expenseItems = new ArrayList<>();
        for (SettlementExpenseItem expenseItem : expenseItems) {
            expenseItem.setMerchantSettlement(this);
        }
        return expenseItems;
    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<SettlementBusinessDebitItem> businessDebitItems = new ArrayList<>();//预支单明细

    public List<SettlementBusinessDebitItem> getBusinessDebitItems() {
        if (businessDebitItems == null) businessDebitItems = new ArrayList<>();
        for (SettlementBusinessDebitItem businessDebitItem : businessDebitItems) {
            businessDebitItem.setMerchantSettlement(this);
        }
        return businessDebitItems;

    }

    /**
     * 重新计算
     */
    public void computeAmt() {
        totalExpenseCost = 0;
        totalCurrentCost = 0;
        totalCostPrevious = 0;
        totalCurrentIncome = 0;
        totalCurrentAmount = 0;
        totalPlatformServiceAmount = 0;
        totalCurrentAddCost = 0;
        totalUnDeductedCost = 0;
        totalBusinessDebitCost = 0;
        totalCurrentPlatformFee = 0;
        shouldSettleBusinessMoney = 0;

        totalExpenseAmount = 0;
        totalPreviousExpense = 0;
        totalUnDeductedExpense = 0;
        totalDebitAmount = 0;
        totalPreviousDebit = 0;
        totalUnDeductedDebit = 0;
        for (SettlementIncomeSummary incomeSummary : incomeSummaries) {
            totalCurrentIncome += incomeSummary.getAmountPayable();
            totalCurrentAmount += incomeSummary.getAmount();
            totalPlatformServiceAmount += incomeSummary.getPlatformServiceFee();
            totalCurrentPlatformFee += incomeSummary.getAdjustmentAmount();
        }
        for (SettlementCostSummary costSummary : costSummaries) {
            totalCostPrevious += costSummary.getPreviousNotDeducted();
            totalCurrentCost += costSummary.getCurrentPeriodActualDeducted();
            totalUnDeductedCost += costSummary.getRemainingDeductibleBalance();
            totalCurrentAddCost += costSummary.getCurrentPeriodShouldDeducted();

        }
        for (SettlementExpenseItem expenseItem : expenseItems) {
            totalExpenseCost += expenseItem.getCurrentAmount();
            totalExpenseAmount += expenseItem.getAmount();
            totalPreviousExpense += expenseItem.getAmountDeducted();
            totalUnDeductedExpense += expenseItem.getBalanceAmount();
        }

        for (SettlementBusinessDebitItem businessDebitItem : businessDebitItems) {
            totalBusinessDebitCost += businessDebitItem.getCurrentAmount();
            totalDebitAmount += businessDebitItem.getPriceDebit();
            totalPreviousDebit += businessDebitItem.getPrincipalRepaid();
            totalUnDeductedDebit += businessDebitItem.getBalanceAmount();
        }
        shouldSettleBusinessMoney = Arith.sub(totalCurrentIncome, totalCurrentCost);
        settleBusinessMoneyTotal = Arith.add(shouldSettleBusinessMoney, preSettleBusinessMoney);
    }

    /**
     * 平台公司
     **/
    @Transient
    private PartyRole platformCompany;


    public PartyRole getPlatformCompany() {
        if (platformCompany != null) return platformCompany;
        String topic = "event:fn.contract.findFirstValidFnContractCompanyByPartnerId";
        if (getMerchant() == null) return null;
        String platformCompanyId = (String) EventUtil.sendSynEvent(this, topic, MapUtil.mapper("partnerId", getMerchant().getId())).stream().findFirst().get();
        if (!StringUtils.isEmpty(platformCompanyId)) {
            platformCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne(platformCompanyId, "Company"));
            platformCompany = MapUtil.getO(MapUtil.mapped(platformCompany), PartyRole.class);
        }
        return platformCompany;
    }


    @Transient
    private boolean pic;

    /**
     * 销售部门
     **/

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("销售部门")
    private Dept dept;


    public Dept getDept() {
        if (dept != null) return dept;
        if(getMerchant() == null) return null;
        dept = (Dept) JpaUtil.getImplementation(SpringManager.getBean(DeptRepository.class).findByPartyRoleAndDeptType(getMerchant().getId(), "000007"));
        dept = MapUtil.getO(MapUtil.mapped(dept), Dept.class);
        return dept;
    }

    public Enumeration getFnTag() {
        if(getMerchant() == null) return null;
        return SpringManager.getBean(StoreRepository.class).findOne(SpringManager.getBean(DeptRepository.class)
                .findByPartyRoleAndDeptType(getMerchant().getId(), "000007").getId()).getFnTag();
    }


    /**
     * 1001公司
     **/
    @Transient
    private PartyRole theCompany;


    public PartyRole getTheCompany() {
        if (theCompany != null) return theCompany;
        theCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne("1001", "Company"));
        theCompany = MapUtil.getO(MapUtil.mapped(theCompany), PartyRole.class);
        return theCompany;
    }

}
